package io.renren.modules.simida.service.impl;

import com.alibaba.fastjson.JSONObject;
import io.renren.common.utils.Constant;
import io.renren.common.utils.StringUtil;
import io.renren.datasource.annotation.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.simida.dao.SysDictDao;
import io.renren.modules.simida.entity.SysDictEntity;
import io.renren.modules.simida.service.SysDictService;


@Service("sysDictService")
public class SysDictServiceImpl extends ServiceImpl<SysDictDao, SysDictEntity> implements SysDictService {
    @Autowired
    private SysDictDao sysDictDao;

    @Override
    @DataSource(Constant.DB_SLAVE_SIMIDA)
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SysDictEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtil.isNotEmpty(params.get("type")), "type", params.get("type"));
        queryWrapper.eq("del_flag", 0);
        IPage<SysDictEntity> page = this.page(
                new Query<SysDictEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    @DataSource(Constant.DB_SLAVE_SIMIDA)
    public SysDictEntity queryById(Long id) {
        return super.getById(id);
    }

    @Override
    @DataSource(Constant.DB_SLAVE_SIMIDA)
    public boolean saveOne(SysDictEntity sysDictEntity) {
        return super.save(sysDictEntity);
    }

    @Override
    @DataSource(Constant.DB_SLAVE_SIMIDA)
    public boolean updateOneById(SysDictEntity sysDict) {
        return super.updateById(sysDict);
    }

    @Override
    @DataSource(Constant.DB_SLAVE_SIMIDA)
    public void logicDeleteBatch(List<Long> ids) {
        //逻辑删除
        sysDictDao.updateBatchDelFlag(ids);
    }

    @Override
    @DataSource(Constant.DB_SLAVE_SIMIDA)
    public List<JSONObject> queryAllDictTypes() {
        QueryWrapper<SysDictEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.groupBy("type");
        List<SysDictEntity> list = this.list(queryWrapper);
        return list.stream().map(sysDictEntity -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("value", sysDictEntity.getType());
            jsonObject.put("label", sysDictEntity.getName());
            return jsonObject;
        }).collect(Collectors.toList());
    }

}